package chen.web.user;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


import org.dom4j.Attribute;
import org.dom4j.DocumentException;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;


public class RoleManagerImpl implements RoleManager{

	private static final String RoleXmlPath = RoleManagerImpl.class.getResource("roles.xml").getPath();
	private static Document doc = loadDocument();
	
	private static final String RootNodeName = "roles";
	private static final String RoleNodeName = "role";
	private static final String RoleIdAttributeName = "id";
	private static final String NameNodeName = "name";
	private static final String DescriptionNodeName = "description";
	private static final String LevelNodeName = "level";
	
	@Override
	public void createRole(Role role) {
		// TODO Auto-generated method stub
		role.setId(0);
		persist(role);
	}

	@Override
	public void delete(Role role) {
		// TODO Auto-generated method stub
		Node roleNode = getById(role.getId());
		if(roleNode !=null)	roleNode.detach();
	}

	@Override
	public List<Role> getAllRoles() {
		// TODO Auto-generated method stub
		List<Role> list = new ArrayList<Role>();
		List<?> nodeList = doc.selectNodes("//@id");
		Iterator<?> iter = nodeList.iterator();
		while(iter.hasNext()){
			Attribute attr = (Attribute) iter.next();
			int id = Integer.parseInt(attr.getValue());
			Role role = getRole(id);
			if(role != null)
				list.add(getRole(id));
		}
		return list;
	}
	
	@Override
	public Role getRole(int id) {
		// TODO Auto-generated method stub
		Node roleNode = getById(id);
		if(roleNode == null){
			return null;
		}
		
		Role role = new Role();
		String name = roleNode.selectSingleNode(NameNodeName).getText();
		String description = roleNode.selectSingleNode(DescriptionNodeName).getText();
		int level = Integer.parseInt(roleNode.selectSingleNode(LevelNodeName).getText());
		
		role.setId(id);
		role.setName(name);
		role.setDescription(description);
		role.setLevel(level);
		
		return role;
	}
	
	private Node getById(int id){
		String xpath = new StringBuffer().append("/")
										.append(RootNodeName)
										.append("/")
										.append(RoleNodeName)
										.append("[@")
										.append(RoleIdAttributeName)
										.append("='")
										.append(id)
										.append("']")
										.toString();
		Node roleNode = doc.selectSingleNode(xpath);
		return roleNode;
	}

	@Override
	public void modify(Role role) {
		// TODO Auto-generated method stub
		persist(role);
	}
	
	private void persist(Role role){
/*		int id = role.getId();
		String name = role.getName();
		String description = role.getDescription();
		int level = role.getLevel();
		
		//如果存在id则删除旧的再创建，否则直接创建
		if(id != 0){
			Node roleNode = getById(id);
			if(roleNode != null){
				roleNode.detach();
			}
		} else {
			id = UUID.randomUUID().toString();
		}
		
		Element roleNode = doc.getRootElement().addElement(RoleNodeName);
		roleNode.addAttribute(RoleIdAttributeName, id);
	
		
		Element nameNode = roleNode.addElement(NameNodeName);
		nameNode.setText(name);
		
		Element descriptionNode = roleNode.addElement(DescriptionNodeName);
		descriptionNode.addCDATA(description);
		
		Element levelNode = roleNode.addElement(LevelNodeName);
		levelNode.setText(String.valueOf(level));
		
		storeDocument(doc);
		role.setId(id);*/
	}
	
	private synchronized static Document loadDocument(){
		Document document = null;
		SAXReader saxReader = new SAXReader();
		try {
			document = saxReader.read(RoleXmlPath);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		return document;
	}
	
	private synchronized static void storeDocument(Document doc){
        OutputFormat format = OutputFormat.createPrettyPrint(); // 设置XML文档输出格式
		try {
			XMLWriter writer = new XMLWriter(new FileWriter(RoleXmlPath), format);
			writer.write(doc);
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	

}
